//
// 网络协议的编解码
// Created by kenny on 25-10-20.
//

#ifndef MCP_PROTOCOL_H
#define MCP_PROTOCOL_H

#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#define START_BYTES 0xAA55
#define END_BYTES 0x55AA
#define MAX_PACKET_SIZE 2048

#pragma pack(push, 1)
typedef struct {
    uint16_t start;
    uint16_t length;
    uint8_t protocol;
    uint8_t version;
    // 消息内容变长，这里不定义
    uint16_t sequence;
    uint16_t checksum;
    uint16_t end;
} CustomProtocolHeader;
#pragma pack(pop)

// 数据包内容结构
#pragma pack(push, 1)
typedef struct {
    uint8_t encrypt;           // 0x00不加密，0x01加密
    uint8_t response_protocol; // 响应协议号
    uint16_t response_sequence; // 响应序列号
    // 后面是变长的数据内容
} PacketDataHeader;
#pragma pack(pop)

typedef struct {
    uint8_t protocol;
    uint8_t version;
    uint16_t sequence;
    uint8_t* data;          // 包含 PacketDataHeader + 实际数据
    uint16_t data_length;
} CustomPacket;

extern const char* encryption_key;

// CRC16计算
uint16_t calculate_crc16(const uint8_t* data, uint16_t length);

// 创建数据包内容
int create_data(uint8_t encrypt, uint8_t protocol, uint16_t sequence, const char* message,
                uint8_t* output, uint16_t* output_length);

// 创建完整数据包
int create_packet(uint8_t protocol, uint8_t version, const char* message, uint16_t sequence,
                  uint8_t encrypt, uint8_t resp_protocol, uint16_t resp_sequence,
                  uint8_t* output, uint16_t* output_length);

// 解析数据包
int parse_packet(const uint8_t* input, uint16_t input_length, CustomPacket* packet);

// 解析数据包内容
int parse_packet_data(const uint8_t* data, uint16_t data_length, uint8_t* encrypt,
                     uint8_t* resp_protocol, uint16_t* resp_sequence, char** message);

// 释放数据包内存
void free_packet(CustomPacket* packet);

// 取序列号
uint16_t get_next_sequence(void);

#endif